var CANVAS_WIDTH = 1000 , CANVAS_HEIGHT = 600;
var mycanvas;
var stage;
var sprite;

window.onload = function (){
    mycanvas = document.getElementById("canvas");
    mycanvas.width = CANVAS_WIDTH;
    mycanvas.height = CANVAS_HEIGHT;

    stage = new createjs.Stage(mycanvas);
    stage.addEventListener("stagemousedown",clickHandle);
    stage.addEventListener("stagemousemove",moveHandle);

    var data = {
        images:["2.png"],
        frames:{width:20,height:20,regX:10,regY:10}
    };
    sprite = new createjs.Sprite(new createjs.SpriteSheet(data));
    createjs.Ticker.setFPS(20);
    createjs.Ticker.addEventListener("tick",handle);
};
function handle(event){
    //console.log(stage);
    var  num = stage.getNumChildren();
    for( var i=num-1 ; i>=0 ; i--){
        var star = stage.getChildAt(i);
        //console.log(i);
        star.vX += 1;
        star.vY += 2;

        star.x += star.vX;
        star.y += star.vY;
        star.alpha += star.vA;
        star.scaleX = star.scaleY = star.scaleX+star.vS;
        if(star.alpha<=0 || star.y>mycanvas.height){
            stage.removeChildAt(i);
        }
    }
    stage.update(event);
}
function clickHandle(){
    addStar(Math.random()*200+100,stage.mouseX,stage.mouseY,2);
}
function moveHandle(){
    addStar(Math.random()*2+1,stage.mouseX,stage.mouseY,1);
}
function addStar(count,x,y,speed){
    for(var i=0 ; i<count ;i++){
        var star = sprite.clone();
        star.x = x;
        star.y = y;
        star.alpha = Math.random()*0.5+0.5;
        star.scaleX = star.scaleY = Math.random()+0.3;

        var a = Math.PI*2*Math.random();
        var v = (Math.random()-0.5)*30*speed;
        star.vX = Math.cos(a)*v;
        star.vY = Math.sin(a)*v;
        star.vS = (Math.random() - 0.5)*0.2;
        star.vA = -Math.random()*0.05-0.01;
        stage.addChild(star);
    }
}